﻿using RLRT.Common;
using RLRT.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace RLRT.Web
{
    public partial class ItemsPickReturn : LocalPage
    {
        #region 属性

        /// <summary>
        /// 页面类别 1杂项领用 2料品报废
        /// </summary>
        private int CurrentType
        {
            get
            {
                object tempObject = ViewState["CurrentType"];
                return (tempObject != null) ? (int)tempObject : 0;
            }
            set
            {
                ViewState["CurrentType"] = value;
            }
        }

        #endregion

        /// <summary>
        /// 页面加载
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                #region 验证权限

                #endregion

                #region 获取参数

                string type = Request.QueryString["PageType"];
                if (type != null && type.Trim().Length != 0)
                {
                    this.CurrentType = Util.ToInt(type);
                }

                #endregion

                //初始化
                this.Initialize();
                this.BindList();
            }

            #region 页面标题

            PageTitle.Text = this.CurrentType == 1 ? "杂项领用" : "料品报废";

            this.Title = PageTitle.Text;

            #endregion

            #region 页面要素


            #endregion
        }

        #region 初始化

        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            #region 页面内容

            using (RTProvider rtProvider = new RTProvider())
            {
                var whs = rtProvider.GetWarehouseList();
                LocalGlobal.BindListItems(WhCode, whs.DefaultView, "wmdes", "wmwhs", true);
            }

            //1杂项领用 2料品报废
            if (this.CurrentType == 1)
            {
                PickNoCaption.Text = "领料单号";
                PickQtyCaption.Text = "领用数量";
                PickDateCaption.Text = "领用日期";
            }
            else
            {
                PickNoCaption.Text = "报废单号";
                PickQtyCaption.Text = "报废数量";
                PickDateCaption.Text = "报废日期";
            }

            this.WhCode.SelectedIndex = -1;
            this.PickNo.Text = string.Empty;
            this.BomNo.Text = string.Empty;
            this.BomName.Text = string.Empty;
            this.Spec.Text = string.Empty;
            this.Material.Text = string.Empty;
            this.UM.Text = string.Empty;
            this.Remark.Text = string.Empty;
            this.PickQty.Text = string.Empty;
            this.PickDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

            #endregion

            //绑定列表
            //this.BindList();
        }

        #endregion

        #region 绑定数据

        protected void BomNo_TextChanged(object sender, EventArgs e)
        {
            if (this.BomNo.Text.Trim().Length > 0)
            {
                using (RTProvider rtProvider = new RTProvider())
                {
                    var info = rtProvider.GetItemInfo(this.BomNo.Text.Trim());
                    if (info != null)
                    {
                        this.BomName.Text = info["prloutno"].ToString().Trim();
                        this.Spec.Text = info["prlrule"].ToString().Trim();
                        this.Material.Text = info["prlpicno"].ToString().Trim();
                        this.UM.Text = info["prlum"].ToString().Trim();
                    }
                    else
                    {
                        this.BomName.Text = string.Empty;
                        this.Spec.Text = string.Empty;
                        this.Material.Text = string.Empty;
                        this.UM.Text = string.Empty;
                    }
                }
            }
        }

        /// <summary>
        /// 绑定列表
        /// </summary>
        private void BindList()
        {
            ViewState["ViewDT"] = this.CreateTable();
            this.BindTempData();
        }

        #endregion

        #region 操作

        /// <summary>
        /// 新增List临时行
        /// </summary>
        protected void CreateButton_Click(object sender, EventArgs e)
        {
            var table = ViewState["ViewDT"] as DataTable;
            var newRow = table.NewRow();
            newRow["whcode"] = WhCode.SelectedValue.Trim();
            newRow["prltno"] = BomNo.Text.Trim();
            newRow["bomnam"] = BomName.Text.Trim();
            newRow["bommat"] = Material.Text.Trim();
            newRow["bomspec"] = Spec.Text.Trim();
            newRow["prlum"] = UM.Text.Trim();
            newRow["pickqty"] = PickQty.Text.Trim();
            newRow["pickdate"] = PickDate.Text.Trim();
            newRow["remark"] = Remark.Text.Trim();

            //保存临时数据后重新绑定gridview
            table.Rows.Add(newRow);

            ViewState["ViewDT"] = table;
            BindTempData();
        }

        /// <summary>
        /// 删除List临时行
        /// </summary>
        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            DataTable table = ViewState["ViewDT"] as DataTable;

            bool deleted = false;
            foreach (GridViewRow row in List.Rows)
            {
                HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                if (rowCheckControl.Checked)
                {
                    var whCode = row.Cells[2].Text.Trim(); //仓库
                    var prltno = row.Cells[3].Text.Trim(); //工件号

                    foreach (DataRow dr in table.Rows)
                    {
                        if (dr["whcode"].ToString().Trim() == whCode && dr["prltno"].ToString().Trim() == prltno)
                        {
                            table.Rows.Remove(dr);
                            break;
                        }
                    }
                    //有项被删除
                    deleted = true;
                }
            }
            if (deleted)
            {
                ViewState["ViewDT"] = table;
                BindTempData();
            }
            else
            {
                this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            SqlConnection con = LocalGlobal.DbConnect();
            con.Open();
            SqlTransaction tran = con.BeginTransaction();//使用事务
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.Transaction = tran;

            try
            {
                using (RTProvider rtProvider = new RTProvider())
                {
                    bool flag = false;
                    string pickNo = this.PickNo.Text.Trim(); //领用、报废单号

                    int seq = 0;
                    foreach (GridViewRow row in List.Rows)
                    {
                        seq++;
                        string whCode = row.Cells[2].Text.Trim();
                        //string pickqty = row.Cells[7].Text.Trim(); //领用数量、报废数量
                        string pickqty = ((TextBox)row.FindControl("pickqty")).Text.Trim(); //领用数量
                        string pickdate = ((TextBox)row.FindControl("pickdate")).Text.Trim(); //日期
                        string remark = ((TextBox)row.FindControl("remark")).Text.Trim(); //备注

                        //新增领用记录
                        cmd.CommandText = rtProvider.InsertPickSql(pickNo, seq.ToString(), whCode, "", "0", row.Cells[3].Text.Trim(), row.Cells[4].Text.Trim(), row.Cells[6].Text.Trim(), row.Cells[5].Text.Trim(), pickqty, row.Cells[7].Text.Trim(), pickdate, remark);
                        cmd.ExecuteNonQuery();

                        //更新库存数量
                        cmd.CommandText = rtProvider.DecreaseInventorySql(whCode, row.Cells[3].Text.Trim(), pickqty);
                        cmd.ExecuteNonQuery();

                        flag = true;
                    }

                    if (!flag)
                    {
                        this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
                        tran.Rollback();
                        return;
                    }
                }
            }
            catch (Exception error)
            {
                tran.Rollback();
                this.ShowErrorMessage("操作失败。" + error.Message);
                return;
            }

            tran.Commit();

            Initialize();
            this.BindList();
        }

        /// <summary>
        /// 取消
        /// </summary>
        protected void CancelButton_Click(object sender, EventArgs e)
        {
            this.Initialize();
        }

        #endregion

        #region 创建表结构及绑定
        protected DataTable CreateTable()
        {
            //定义table结构   
            DataTable dt1 = new DataTable();
            //不设置 默认为System.String  
            dt1.Columns.Add("whcode");
            dt1.Columns.Add("prltno");
            dt1.Columns.Add("bomnam");
            dt1.Columns.Add("bommat");
            dt1.Columns.Add("bomspec");
            dt1.Columns.Add("prlum");
            dt1.Columns.Add("pickqty");
            dt1.Columns.Add("pickdate");
            dt1.Columns.Add("remark");
            //dt1.Rows.Add(dt1.NewRow());
            //ViewState["ViewDT"] = dt1;
            return dt1;
        }

        protected void BindTempData()
        {
            this.List.DataSource = ViewState["ViewDT"] as DataTable;
            this.List.DataBind();

            if (List.HeaderRow != null)
            {
                if (this.CurrentType == 1) //杂项领用
                {
                    this.List.HeaderRow.Cells[8].Text = "领用数量";
                    this.List.HeaderRow.Cells[9].Text = "领用日期";
                }
                else  //料品报废
                {
                    this.List.HeaderRow.Cells[8].Text = "报废数量";
                    this.List.HeaderRow.Cells[9].Text = "报废日期";
                }
            }
        }

        #endregion
    }
}